import React, { useState, useEffect } from 'react';
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom';
import { 
  Layout, 
  Menu, 
  Button, 
  Drawer, 
  Space,
  Dropdown,
  Avatar,
  Divider
} from 'antd';
import { useRouteLoading } from '../hooks/useRouteLoading';
import { Loading } from '../components/ui';

import { 
  MenuOutlined, 
  HomeOutlined,
  AppstoreOutlined,
  ProjectOutlined,
  TeamOutlined,
  LoginOutlined,
  UserOutlined,
  LogoutOutlined,
  SettingOutlined,
  PhoneOutlined,
  MailOutlined,
  EnvironmentOutlined,
  WechatOutlined,
  QqOutlined,
  CustomerServiceOutlined,
  ContactsOutlined
} from '@ant-design/icons';
import { useAuthStore } from '../services/store';
import { ContactModal } from '../components/ui';
import { APP_CONFIG } from '../constants';
import type { MenuProps } from 'antd';

const { Header, Content, Footer } = Layout;

const WebLayout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, isAuthenticated, logout } = useAuthStore();
  const routeLoading = useRouteLoading();

  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [contactModalOpen, setContactModalOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 50);
    };
    
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // 路由切换时自动返回顶部
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [location.pathname]);

  // 导航菜单项
  const menuItems: MenuProps['items'] = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: <Link to="/">首页</Link>
    },
    {
      key: '/products',
      icon: <AppstoreOutlined />,
      label: <Link to="/products">产品</Link>
    },
    {
      key: '/cases',
      icon: <ProjectOutlined />,
      label: <Link to="/cases">案例</Link>
    },
    {
      key: '/about',
      icon: <TeamOutlined />,
      label: <Link to="/about">关于</Link>
    }
  ];

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料'
    },
    {
      key: 'admin',
      icon: <SettingOutlined />,
      label: <Link to="/cxggad">管理后台</Link>
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: () => {
        logout();
        navigate('/');
      }
    }
  ];

  // 获取当前选中的菜单项
  const selectedKeys = [location.pathname];

  return (
    <Layout className="min-h-screen">
      {/* 导航栏 */}
      <Header 
        className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ease-in-out ${
          scrolled 
            ? 'bg-white/95 backdrop-blur-md shadow-lg border-b border-gray-100/50' 
            : 'bg-white/90 backdrop-blur-sm'
        }`}
        style={{ padding: '0', height: '72px', lineHeight: '72px' }}
      >
        <div className="container flex items-center justify-between h-full px-4">
          {/* Logo */}
          <Link to="/" className="flex items-center space-x-3 group">
            <div className="relative">
              <img 
                src="/logo.png"
                alt={APP_CONFIG.siteName}
                className="h-10 w-auto transition-transform duration-300 group-hover:scale-105"
              />
              <div className="absolute inset-0 bg-gradient-to-r from-primary-500/20 to-secondary-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-xl"></div>
            </div>
            <span className="text-2xl font-bold bg-gradient-to-r from-primary-600 to-secondary-600 bg-clip-text text-transparent flex items-center">
              {APP_CONFIG.siteName}
            </span>
          </Link>

          {/* 桌面端菜单 */}
          <div className="hidden lg:flex items-center flex-1 justify-center">
            <nav className="flex items-center space-x-8">
              {menuItems.map((item) => (
                <Link
                   key={item.key}
                   to={item.key as string}
                   className={`relative px-6 py-3 text-base font-medium transition-all duration-300 group rounded-lg ${
                     selectedKeys.includes(item.key as string)
                       ? 'text-white bg-gradient-to-r from-primary-500 to-primary-600 shadow-lg shadow-primary-500/25'
                       : 'text-gray-700 hover:text-primary-600 hover:bg-primary-50'
                   }`}
                 >
                   <span className="relative z-10 flex items-center space-x-2">
                     {(item as any).icon}
                     <span>{typeof (item as any).label === 'object' && 'props' in (item as any).label ? (item as any).label.props.children : (item as any).label}</span>
                   </span>
                  {/* 悬停效果背景 */}
                  {!selectedKeys.includes(item.key as string) && (
                    <div className="absolute inset-0 bg-gradient-to-r from-primary-500/5 to-secondary-500/5 rounded-lg opacity-0 group-hover:opacity-100 transition-all duration-300"></div>
                  )}
                  {/* 底部指示线 */}
                  <div className={`absolute bottom-0 left-1/2 transform -translate-x-1/2 h-1 bg-gradient-to-r from-primary-400 to-secondary-400 rounded-full transition-all duration-300 ${
                    selectedKeys.includes(item.key as string)
                      ? 'w-8 opacity-100'
                      : 'w-0 opacity-0 group-hover:w-6 group-hover:opacity-70'
                  }`}></div>
                </Link>
              ))}
            </nav>
          </div>
          
          {/* 右侧按钮 */}
          <div className="hidden lg:flex items-center space-x-4">
            <Button 
              type="primary" 
              size="large"
              onClick={() => setContactModalOpen(true)}
              icon={<PhoneOutlined />}
              className="btn-primary hover-glow"
            >
              免费咨询报价
            </Button>
          </div>

          {/* 移动端菜单按钮 */}
          <Button
            type="text"
            size="large"
            icon={<MenuOutlined className="text-xl" />}
            onClick={() => setMobileMenuOpen(true)}
            className="lg:hidden p-3 hover:bg-primary-50 hover:text-primary-600 transition-colors duration-300"
          />
        </div>
      </Header>

      {/* 移动端抽屉菜单 */}
      <Drawer
        title={
          <div className="flex items-center space-x-3">
            <img 
              src="/logo.png"
              alt={APP_CONFIG.siteName}
              className="h-8 w-auto"
            />
            <span className="text-lg font-bold bg-gradient-to-r from-primary-600 to-secondary-600 bg-clip-text text-transparent">
              {APP_CONFIG.siteName}
            </span>
          </div>
        }
        placement="right"
        onClose={() => setMobileMenuOpen(false)}
        open={mobileMenuOpen}
        width={320}
        className="mobile-drawer"
        styles={{
          header: {
            borderBottom: '1px solid #f0f0f0',
            padding: '16px 24px'
          },
          body: {
            padding: '24px'
          }
        }}
      >
        <div className="space-y-6">
          {/* 导航菜单 */}
          <nav className="space-y-2">
            {menuItems.map((item) => (
              <Link
                key={item.key}
                to={item.key as string}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl transition-all duration-300 group ${
                  selectedKeys.includes(item.key as string)
                    ? 'bg-gradient-to-r from-primary-50 to-secondary-50 text-primary-600 border border-primary-200'
                    : 'text-gray-700 hover:bg-gray-50 hover:text-primary-600'
                }`}
              >
                <span className={`text-lg transition-colors duration-300 ${
                   selectedKeys.includes(item.key as string)
                     ? 'text-primary-600'
                     : 'text-gray-500 group-hover:text-primary-600'
                 }`}>
                   {(item as any).icon}
                 </span>
                 <span className="font-semibold">
                   {typeof (item as any).label === 'object' && 'props' in (item as any).label ? (item as any).label.props.children : (item as any).label}
                 </span>
              </Link>
            ))}
          </nav>
          
          <Divider className="my-6" />
          
          {/* 操作按钮 */}
          <div className="space-y-4">
            <Button 
              type="primary" 
              size="large"
              block
              onClick={() => {
                setContactModalOpen(true);
                setMobileMenuOpen(false);
              }}
              icon={<PhoneOutlined />}
              className="btn-primary h-12 text-base font-semibold"
            >
              免费咨询报价
            </Button>
            
            {/* 联系信息 */}
            <div className="bg-gray-50 rounded-xl p-4 space-y-3">
              <div className="text-sm font-semibold text-gray-600 mb-2">快速联系</div>
              <div className="flex items-center space-x-2 text-sm text-gray-600">
                <PhoneOutlined className="text-primary-500" />
                <span>400-123-4567</span>
              </div>
              <div className="flex items-center space-x-2 text-sm text-gray-600">
                <WechatOutlined className="text-green-500" />
                <span>微信咨询</span>
              </div>
            </div>
          </div>
        </div>
      </Drawer>

      {/* 主要内容区域 */}
      <Content style={{ marginTop: '64px' }}>
        {routeLoading ? (
          <div className="min-h-screen flex items-center justify-center">
            <Loading 
              spinning={true} 
              text="页面加载中..." 
              size="large" 
            />
          </div>
        ) : (
          <Outlet />
        )}
      </Content>

      {/* 页脚 */}
      <Footer className="bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 text-white">
        <div className="max-w-7xl mx-auto px-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8 py-12">
            {/* 公司信息 */}
            <div className="text-left">
              <div className="flex items-center space-x-3 mb-6">
                <img 
                  src="/logo.png"
                  alt={APP_CONFIG.siteName}
                  className="h-10 w-auto"
                />
                <span className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                  {APP_CONFIG.siteName}
                </span>
              </div>
              <p className="text-gray-300 mb-6 leading-relaxed text-sm">
                专业从事广告设计制作12年，服务3800+客户，提供品牌视觉、户外广告、展览物料等一站式广告解决方案
              </p>
              <div className="flex space-x-3">
                <div className="w-10 h-10 bg-green-600 rounded-full flex items-center justify-center hover:bg-green-500 transition-colors cursor-pointer">
                  <WechatOutlined className="text-white" />
                </div>
                <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center hover:bg-blue-500 transition-colors cursor-pointer">
                  <QqOutlined className="text-white" />
                </div>
              </div>
            </div>

            {/* 营业时间 */}
            <div className="text-left">
              <h3 className="text-lg font-semibold mb-6 text-white">营业时间</h3>
              <div className="space-y-3">
                <div className="flex justify-between text-gray-300 text-sm">
                  <span className="font-medium">周一至周五</span>
                  <span>9:00 - 18:00</span>
                </div>
                <div className="flex justify-between text-gray-300 text-sm">
                  <span className="font-medium">周六</span>
                  <span>9:00 - 17:00</span>
                </div>
                <div className="flex justify-between text-gray-300 text-sm">
                  <span className="font-medium">周日</span>
                  <span>休息</span>
                </div>
              </div>
            </div>

            {/* 联系信息 */}
            <div className="text-left">
              <h3 className="text-lg font-semibold mb-6 text-white">联系我们</h3>
              <div className="space-y-4">
                <div className="flex items-center space-x-3 text-gray-300">
                  <div className="w-8 h-8 bg-blue-600/20 rounded-lg flex items-center justify-center">
                    <PhoneOutlined className="text-blue-400" />
                  </div>
                  <span className="text-sm">{APP_CONFIG.phone}</span>
                </div>
                <div className="flex items-center space-x-3 text-gray-300">
                  <div className="w-8 h-8 bg-green-600/20 rounded-lg flex items-center justify-center">
                    <MailOutlined className="text-green-400" />
                  </div>
                  <span className="text-sm">{APP_CONFIG.email}</span>
                </div>
                <div className="flex items-start space-x-3 text-gray-300">
                  <div className="w-8 h-8 bg-purple-600/20 rounded-lg flex items-center justify-center mt-0.5">
                    <EnvironmentOutlined className="text-purple-400" />
                  </div>
                  <span className="text-sm leading-relaxed">{APP_CONFIG.address}</span>
                </div>
              </div>
            </div>
          </div>

          {/* 版权信息 */}
          <div className="border-t border-gray-700 pt-6 pb-4">
            <div className="flex flex-col md:flex-row justify-between items-center space-y-2 md:space-y-0 text-gray-400 text-sm">
              <p>&copy; 2024 {APP_CONFIG.name}. 保留所有权利。</p>
              <p>ICP备案号：粤ICP备xxxxxxxx号</p>
            </div>
          </div>
        </div>
      </Footer>

      {/* 联系弹窗 */}
      <ContactModal
        open={contactModalOpen}
        onClose={() => setContactModalOpen(false)}
      />
      

    </Layout>
  );
};

export default WebLayout;